﻿using System.IO;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using System;

namespace SingleBlog.Web
{
    using Framework;
    public class Program
    {
        public static void Main(string[] args)
        {
            var hostBuilder = BuildWebHost(args);
            var build = hostBuilder.Build();
            build.Run();
        }

        public static IWebHostBuilder BuildWebHost(string[] args)
        {

            var config = new SingleBlogConfigurationBuilder(new ConfigurationBuilder()).GetConfiguration();
            var builder = WebHost.CreateDefaultBuilder(args);
            builder.UseConfiguration(config);
            builder.UseStartup(Type.GetType(config["Startup"]));
            builder.UseContentRoot(Directory.GetCurrentDirectory());
            builder.UseEnvironment(config["Environment"]);

            var port = config.GetValue<int>("Port");
            switch (config["HttpServer"])
            {
                case "Kestrel":
                    builder.UseKestrel(option =>
                    {
                        option.Listen(System.Net.IPAddress.Loopback, port);
                    });
                    break;
                case "IISIntegration":
                    builder.UseIISIntegration();
                    break;
                case "HttpSys":
                    builder.UseHttpSys();
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            if (!config["BindUrls"].IsNullOrWhiteSpace())
            {
                builder.UseUrls(config["BindUrls"].Split(','));
            }

            return builder;
        }
    }    
}
